const config = require('./server_config');
const axios = require('axios');
const APPID = config.wx.appid;
const SECRET = config.wx.secret;

let cached = { token: '', expire: 0 };

async function getAccessToken() {
    const now = Date.now();
    if (cached.token && now < cached.expire) return cached.token;

    const { data } = await axios.get(
        'https://api.weixin.qq.com/cgi-bin/token',
        {
            params: {
                grant_type: 'client_credential',
                appid: APPID,
                secret: SECRET
            }
        }
    );
    if (data.errcode) throw new Error(data.errmsg);

    cached.token = data.access_token;      // 2 小时有效期
    cached.expire = now + (data.expires_in - 60) * 1000; // 提前 60 秒续
    return cached.token;
}

module.exports = { getAccessToken };